package com.alm.token.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.BaseEntity;
import com.alm.token.ui.data.bean.G12CanData;
import com.alm.token.ui.data.bean.UserListLHData;
import com.alm.token.ui.data.bean.ZhuijiashowData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.QuantitativeOrderOpenAddView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.haozhang.lib.SlantedTextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import baibeiwallet.Constant;
import butterknife.BindView;
import butterknife.ButterKnife;

public class QuantitativeOrderDetailActivity extends BaseActivity implements QuantitativeOrderOpenAddView<Object> {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.centerItem)
    TextView centerItem;
    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.zhuijia_btn)
    TextView zhuijiaBtn;
    @BindView(R.id.close_btn)
    TextView closeBtn;
    @BindView(R.id.img_ordertype)
    SlantedTextView imgOrdertype;
    @BindView(R.id.tv_orderid)
    TextView tvOrderid;
    @BindView(R.id.tv_shuliang)
    TextView tvShuliang;
    @BindView(R.id.tv_shuliang2)
    TextView tvShuliang2;
    @BindView(R.id.tv_yaoqingma)
    TextView tvYaoqingma;
    @BindView(R.id.tv_lejiday)
    TextView tvLejiday;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.tv_yuji)
    TextView tvYuji;
    @BindView(R.id.tv_leji)
    TextView tvLeji;
    private RefreshLoadMoreManager<OrderEntity> manager;
    private UserListLHData.DataBean dataBean;
    private int ActivityForResultCode = 2;
    private JSONObject shouyiJson;//* shouyi : [{date=1546865466000, money=289.5126}]  * lejiday : 1
    private String strShouyi = "";

    public static int AppendSucc = -1;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_quantitative_order_detail;
    }

    @Override
    protected void initVariables() {
        dataBean = (UserListLHData.DataBean) getIntent().getSerializableExtra("databean");
        strShouyi = "{shouyi:" + dataBean.getShouyi().replace("=", ":") + "}";
        dataBean.setShouyi(strShouyi);
//        showToast("strShouyi=" + strShouyi);
//        if (Integer.parseInt(dataBean.getLejiday().isEmpty() ? "0" : dataBean.getLejiday()) != 0) {

        try {
            shouyiJson = new JSONObject(dataBean.getShouyi());//shouyi : [{date=1546865466000, money=289.5126}]
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        }
        AppendSucc = -1;
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this)
                .setTitle(getString(R.string.title_hint_item29))
                .setRightIcon(R.drawable.lh_order, this);

        tvOrderid.setText(dataBean.getOrderid());
        DecimalFormat dec = new DecimalFormat("0.0000");
        StringBuffer shuliang1 = new StringBuffer();
        if (dataBean.getBizhong() != null && dataBean.getBizhong().size() != 0) {
            for (int i = 0; i <dataBean.getBizhong().size() ; i++) {
                shuliang1 .append(dec.format(dataBean.getBizhongMoney().get(i)) + " "+dataBean.getBizhong().get(i)+(i==dataBean.getBizhong().size()-1?"":i%2==1?"\n":"/"));
            }
        } else {
            shuliang1 .append(dec.format(0) + " ETH");
        }
        String shuliang2 = dataBean.getBizhong1() + " " + dec.format(dataBean.getBizhongMoney1());
        tvShuliang.setText(shuliang1.toString());
        tvShuliang2.setText(shuliang2);
//        tvShuliang.setText(dec.format(Double.parseDouble(dataBean.getShuliang().isEmpty() ? "0" : dataBean.getShuliang())));
        tvLejiday.setText(dataBean.getLejiday().replace("-","") + "Days");
        tvStart.setText("Start: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getStart())).split(" ")[0]);

        if (dataBean.getEnd() != null && Long.parseLong(dataBean.getEnd()) != 0 && Integer.parseInt(dataBean.getOrderStatus()) != 0) {
//            tvEnd.setVisibility(View.VISIBLE);
//            tvEnd.setText("结束时间:" + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getEnd())).split(" ")[0]);
            tvYuji.setText("End: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getYuji())).split(" ")[0]);
        } else {
            tvYuji.setText("Expire: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getYuji())).split(" ")[0]);

//            tvEnd.setVisibility(View.GONE);
        }

//        tvYuji.setText("Expire:" + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(dataBean.getYuji())).split(" ")[0]);
        DecimalFormat dec1 = new DecimalFormat("0.00");
        tvLeji.setText("Total：" + dec1.format(Double.parseDouble(dataBean.getLeji().isEmpty() ? "0" : dataBean.getLeji())));

        if (Integer.parseInt(dataBean.getOrderStatus()) != 0) {
            imgOrdertype.setText(getString(R.string.alphago_hint_ygb))
                    .setTextColor(getResources().getColor(R.color.quanlitative_flag3))
                    .setSlantedBackgroundColor(getResources().getColor(R.color.quanlitative_flag2))
                    .setTextSize(11)
                    .setSlantedLength(55)
                    .setMode(SlantedTextView.MODE_RIGHT_TRIANGLE);
            zhuijiaBtn.setVisibility(View.GONE);
            closeBtn.setVisibility(View.GONE);
            rightItem.setVisibility(View.GONE);
//            new ActionBarHelper(this)
//                    .setTitle("量化订单");
//
//            rightItem.setOnClickListener(null);
        } else {
            imgOrdertype.setText(getString(R.string.alphago_hint_jxz))
                    .setTextColor(Color.WHITE)
                    .setSlantedBackgroundColor(getResources().getColor(R.color.quanlitative_flag1))
                    .setTextSize(11)
                    .setSlantedLength(55)
                    .setMode(SlantedTextView.MODE_RIGHT_TRIANGLE);
            rightItem.setOnClickListener(this);
        }


        closeBtn.setOnClickListener(this);
        zhuijiaBtn.setOnClickListener(this);
        leftItem.setOnClickListener(this);

        initManager();
    }

    private void initManager() {
        OrderAdapter adapter = new OrderAdapter(this);
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .build();

        recyclerView.setNestedScrollingEnabled(false);
    }

    @Override
    protected void loadData() {
//        showToast(dataBean.getOrderid());
        orderEntityList = getTestData();
        if (orderEntityList != null && orderEntityList.size() != 0) {
            recyclerView.setVisibility(View.VISIBLE);
            manager.setData(orderEntityList);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
        }

    }

    List<OrderEntity> orderEntityList = new ArrayList<>();

    private List<OrderEntity> getTestData() {
        orderEntityList.clear();
        //* shouyi : [{date=1546865466000, money=289.5126}]  * lejiday : 1

//        if (!strShouyi.isEmpty()) {
//            ShouyiEntity entity = new Gson().fromJson(strShouyi, ShouyiEntity.class);
//            if (entity != null && entity.getShouyi() != null && entity.getShouyi().size() != 0) {
//                return entity.getShouyi();
//            }
//        }

        if (shouyiJson != null) {
            try {
                JSONArray jsonArray = shouyiJson.getJSONArray("shouyi");
                if (jsonArray != null && jsonArray.length() != 0)

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        OrderEntity entity = new OrderEntity();
                        entity.setDate(object.getString("date"));
                        entity.setMoney(object.getString("money"));
                        entity.setLayoutId(OrderAdapter.LAYOUT_ID);
                        if (Double.parseDouble(object.getString("money")) != 0) {
                            orderEntityList.add(entity);
                        }

                    }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

//        List<OrderEntity> data = new ArrayList<>();
//        for (int i = 0; i < 4; i++) {
//            OrderEntity entity = new OrderEntity();
//            entity.setLayoutId(OrderAdapter.LAYOUT_ID);
//            data.add(entity);
//        }
        return orderEntityList;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_btn:
                Intent intent1 = new Intent(this, QuantitativeOrderCloseActivity.class);
                intent1.putExtra("databean", dataBean);
                startActivityForResult(intent1, ActivityForResultCode);
//                startActivity(QuantitativeOrderCloseActivity.class);
                break;
            case R.id.zhuijia_btn:
//

                Intent intent = new Intent(QuantitativeOrderDetailActivity.this, QuantitativeOrderOpenAddActivity.class);
                intent.putExtra("intentType", 1);
                intent.putExtra("databean", dataBean);
                startActivityForResult(intent, ActivityForResultCode);
//                startActivity(intent);//追加
                break;
            case R.id.leftItem:
                if (AppendSucc == 2) {
                    setResult(AppendSucc);
                }
                finish();
                break;
            case R.id.rightItem:
                startActivity(LH2OrderHistoryActivity.class);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (AppendSucc == 2) {
                setResult(AppendSucc);
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ActivityForResultCode) {
            if (resultCode == QuantitativeOrderOpenAddActivity.AddAppendSucc) {
//                showToast("追加成功，更新追加显示详情页面");
                AppendSucc = 2;
                zhuijiaBtn.setText(getString(R.string.alphago_hint_warn11));
//                zhuijiaBtn.setImageDrawable(getResources().getDrawable(R.drawable.zuijiaappend));
                preenter.getZhuijiashowData(dataBean.getOrderid());
//                preenter.getUserListLHData("100", "1");////////
            }
            if (resultCode == QuantitativeOrderCloseActivity.closeOrderSucc) {
                AppendSucc = 2;
                setResult(AppendSucc);
                finish();
//                preenter.getUserListLHData("100", "1");////////
            }
        }


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void getShowUserXingjiData(Object o) {

    }

    @Override
    public void getAddLhOrderData(Object o) {

    }

    @Override
    public void getAppendOrderData(Object o) {

    }

    @Override
    public void getCloseOrderData(Object o) {

    }

    @Override
    public void getZhuijiashowData(Object o) {
        if (o instanceof ZhuijiashowData) {
            ZhuijiashowData data = (ZhuijiashowData) o;
            if (data.getStatus() == 0) {
                if (data.getData() != null && data.getData().getBizhong1() != null && data.getData().getBizhongMoney1() != null) {
                    dataBean.setBizhong(data.getData().getBizhong1());
                    dataBean.setBizhong1(data.getData().getBizhong2());
                    dataBean.setBizhongMoney(data.getData().getBizhongMoney1());
                    dataBean.setBizhongMoney1(data.getData().getBizhongMoney2());
                }

                DecimalFormat dec = new DecimalFormat("0.0000");

                StringBuffer shuliang1 = new StringBuffer();
                if (dataBean.getBizhong() != null && dataBean.getBizhong().size() != 0) {
                    for (int i = 0; i <dataBean.getBizhong().size() ; i++) {
                        shuliang1 .append(dec.format(dataBean.getBizhongMoney().get(i)) + " "+dataBean.getBizhong().get(i)+(i==dataBean.getBizhong().size()-1?"":i%2==1?"\n":"/"));
                    }
                } else {
                    shuliang1 .append(dec.format(0) + " ETH");
                }
                String shuliang2 = dataBean.getBizhong1() + " " + dec.format(dataBean.getBizhongMoney1());
                tvShuliang.setText(shuliang1.toString());
                tvShuliang.setText(shuliang1.toString());
                tvShuliang2.setText(shuliang2);

//                tvShuliang.setText(dataBean.getShuliang());
            }
        }
    }

    @Override
    public void getUserListLHData(Object o) {

    }

    @Override
    public void getG12CanData(G12CanData g12CanData) {

    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }


    public class OrderEntity extends BaseEntity {
        //    shouyi : [{date=1546865466000, money=289.5126}]

        String date;//
        String money;//

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public String getMoney() {
            return money;
        }

        public void setMoney(String money) {
            this.money = money;
        }
    }


    public class OrderAdapter extends BaseAdapter<OrderEntity> {

        public static final int LAYOUT_ID = R.layout.item_quantitative_order_detail_date_item;

        public OrderAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, OrderEntity item, int itemType) {
            helper.setText(R.id.tv_shouyitime, CommonUtil.getDateTimeFromMillisecond(Long.parseLong(item.getDate())).split(" ")[0]);
            helper.setText(R.id.tv_shouymoney, item.getMoney());

        }

    }
}
